package com.uxsino.rule.util.function;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.function.AbstractVariadicFunction;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;

public class FindFunctionCustom extends AbstractVariadicFunction {

    @Override
    public String getName() {
        return "find";
    }

    @Override
    public AviatorObject variadicCall(Map<String, Object> env, AviatorObject... args) {
        List<JSONObject> result = new ArrayList<JSONObject>();
        @SuppressWarnings("unchecked")
        List<JSONObject> list = (List<JSONObject>) args[0].getValue(env);
        String expression = (String) args[1].getValue(env);
        for (JSONObject obj : list) {
            if ((boolean) AviatorEvaluator.exec(expression, obj)) {
                result.add(obj);
            }
        }
        return new AviatorRuntimeJavaType(result.toArray());
    }

}
